import os
import cv2
from feature_match import list_files_in_directory
from feature import get_features, get_feature_orb, get_feature_akaze, get_feature_brisk
from pre import preProcess


alogrithm_name = ['get_features', 'get_feature_orb', 'get_feature_akaze', 'get_feature_brisk']

# 这里不使用feature_match中的函数，重写
def feature_match(img1, img2, alogrithm_name , ratio=0.9):
    """
    :param img1: 查询图像1
    :param img2: 待匹配的图像2
    :param ratio: 匹配点匹配时，最接近和次接近的比值
    :return matche_img, len(keypoints_raw), len(keypoints_match), len(matches)
    """
    matcher = cv2.BFMatcher()
    keypoints_raw, descriptors_raw, _, _ = globals()[alogrithm_name](img1)
    keypoints_match, descriptors_match, _, _ = globals()[alogrithm_name](img2)
    raw_matches = matcher.knnMatch(descriptors_raw, descriptors_match, k=2)
    matches = []
    for m1, m2 in raw_matches:
        #  如果最接近和次接近的比值小于一个既定的值，
        #  保留这个最接近的值，认为它和其匹配的点为good_match
        if m1.distance < ratio * m2.distance:
            matches.append([m1])
    matche_img = cv2.drawMatchesKnn(img1, keypoints_raw, img2,
                                    keypoints_match, matches, None, flags=2)
    return matche_img, len(keypoints_raw), len(keypoints_match), len(matches)
def alogrithm_accurency(root_val, root_data, name_num = 0):
    """
    :param name:
    :return:score_accurency
    """
    score_accurency = 0
    alogrithm = alogrithm_name[name_num]
    right_count = 0
    for val in os.listdir(root_val):
        val_path = os.path.join(root_val, val)
        print(f'待识别图像名:{val}')
        val_img = cv2.imread(val_path, cv2.IMREAD_GRAYSCALE)
        best_score = 0
        best_name = None
        for file in list_files_in_directory(root_data, val):
            # print(f'正在匹配的图像名{file}')
            match_path = os.path.join(root_data, file)
            match_img = cv2.imread(match_path, cv2.IMREAD_GRAYSCALE)
            match_img, keypoints_raw, keypoints_match, match_size = feature_match(val_img, match_img,
                                                                                  alogrithm, ratio=0.9)
            score = match_size / min(keypoints_raw, keypoints_match)
            if score > best_score:
                best_score = score
                best_name = file
        if val[0] == best_name[0]:
            right_count += 1
        print(f'------------------------{val}图像匹配完成-----------------------')
        print(f'最高匹配得分图像{best_name}')
        print()
    score_accurency = right_count / len(os.listdir(root_val))
    return score_accurency

if __name__ == '__main__':
    root_val = './data/val/'
    root_data = './data/db/'
    name_num = 1
    accurency = alogrithm_accurency(root_val, root_data, name_num)
    print(f'{alogrithm_name[name_num]}准确率:', accurency)